import logging
from lxml import etree
from rest4databases.lib.base import *
from rest4databases.lib.databases import TableNotExistException

log = logging.getLogger(__name__)

class RecordsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py file has
    # a resource setup:
    #     map.resource('record', 'records')


#    def index(self, format='html'):
#        """GET /records: All items in the collection."""
#        # url_for('records')
#        pass

    def index(self, table):
        try:
            c.records = g.database.getRecords(table)
            c.encode_id_fn=g.database.get_encoded_id_fn(table)
            c.record_id=g.database.get_table_pk(table)
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return render('/records/list.mako')
        except TableNotExistException:
            abort(404)

    def create(self, table):
        """POST /records: Create a new item."""
        # url_for('records')
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            record = self._XMLToDict(content)
            id = g.database.insertRecord(table, record)
            del response.headers['Content-Type']
            response.status_code = 201
            return str('/%s/record/%s' % (table, str(id)))
        except TableNotExistException:
            abort(404)

    def new(self, format='html'):
        """GET /records/new: Form to create a new item."""
        # url_for('new_record')
        pass

    def update(self, table, id):
        """PUT /records/id: Update an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(h.url_for('record', id=ID),
        #           method='put')
        # url_for('record', id=ID)
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            fields = self._XMLToDict(content)
            g.database.updateRecord(table, id, fields)
            del response.headers['Content-Type']
            response.status_code = 204
            return
        except TableNotExistException:
            abort(404)

    def delete(self, table, id):
        """DELETE /records/id: Delete an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(h.url_for('record', id=ID),
        #           method='delete')
        # url_for('record', id=ID)
        try:
            g.database.deleteRecord(table, id)
            del response.headers['Content-Type']
            response.status_code = 204
            return
        except TableNotExistException:
            abort(404)

    def show(self, id, format='html'):
        """GET /records/id: Show a specific item."""
        # url_for('record', id=ID)
        pass

    def edit(self, id, format='html'):
        """GET /records/id;edit: Form to edit an existing item."""
        # url_for('edit_record', id=ID)
        pass

    def _XMLToDict(self, xml):
        tree = etree.fromstring(xml)
        result = {}
        for field in tree.xpath('/record/field'):
            result[field.get('name')] = field.text
        return result
